<template>
  <d2-container>
    <el-row>
      <el-col :lg="12">
        <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="120px">
          <el-form-item label="门店" prop="storeName">
            <el-input placeholder="门店" v-model="detailForm.storeName" readonly @focus="fnOpenPopup"></el-input>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input placeholder="标题" v-model="detailForm.title"></el-input>
          </el-form-item>
          <el-form-item label="原价" prop="originalPrice">
            <!-- <el-input-number placeholder="原价" v-model="detailForm.originalPrice" controls-position="right" :min="0" :max="100000"></el-input-number> -->
            <el-input placeholder="原价" v-model="detailForm.originalPrice" controls-position="right"></el-input>
          </el-form-item>
          <!-- <el-form-item label="现价" prop="discountPrice">
                        <el-input-number placeholder="现价" v-model="detailForm.discountPrice" controls-position="right" :min="0" :max="100000"></el-input-number>
          </el-form-item>-->
          <el-form-item label="种类" prop="productCategory">
            <el-select v-model="detailForm.productCategory" placeholder="请选择种类">
              <el-option
                v-for="item in productCategoryList"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="积分" prop="point">
            <el-input-number
              placeholder="积分"
              v-model="detailForm.point"
              controls-position="right"
              :min="0"
              :max="100000"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="开始购买时间" prop="buyStartDate">
            <el-date-picker
              v-model="detailForm.buyStartDate"
              style="width: 100%"
              type="date"
              placeholder="开始购买时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="购买过期时间" prop="buyExpireDate">
            <el-date-picker
              v-model="detailForm.buyExpireDate"
              style="width: 100%"
              type="date"
              placeholder="购买过期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="使用截至时间" prop="useExpireDate">
            <el-date-picker
              v-model="detailForm.useExpireDate"
              style="width: 100%"
              type="date"
              placeholder="允许开始使用时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="允许开始使用时间" prop="useStartDate">
            <el-date-picker
              v-model="detailForm.useStartDate"
              style="width: 100%"
              type="date"
              placeholder="允许开始使用时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="有效类型" prop="useExpireType">
            <el-select v-model="detailForm.useExpireType" placeholder="有效类型">
              <el-option label="永久有效" :value="0"></el-option>
              <el-option label="限时有效" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="false && detailForm.useExpireType === 1"
            label="使用天数"
            prop="useExpireDay"
          >
            <el-input-number
              placeholder="使用天数"
              v-model="detailForm.useExpireDay"
              controls-position="right"
              :min="0"
              :max="100000"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="总发行量" prop="totalCount">
            <el-input-number
              placeholder="总发行量"
              v-model="detailForm.totalCount"
              controls-position="right"
              :min="0"
              :max="100000"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="单人限领" prop="limit">
            <el-input-number
              placeholder="单人限领"
              v-model="detailForm.limit"
              controls-position="right"
              :min="1"
              :max="100000"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="缩略图" required>
            <el-upload
              class="avatar-uploader"
              :http-request="(file) => handleAvatarSuccess(file, 'thumbnail')"
              :show-file-list="false"
            >
              <img v-if="detailForm.thumbnail" :src="detailForm.thumbnail" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="门店展示图" required>
            <el-upload
              class="avatar-uploader"
              :http-request="(file) => handleAvatarSuccess(file, 'foreignImage')"
              :show-file-list="false"
            >
              <img v-if="detailForm.foreignImage" :src="detailForm.foreignImage" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="图片" prop="images">
            <banner v-model="detailForm.images"></banner>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" :rows="2" placeholder="描述" v-model="detailForm.description"></el-input>
          </el-form-item>
          <el-form-item label="详情" prop="detail">
            <simpleRich v-model="detailForm.detail"></simpleRich>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
            <el-button @click="resetForm('detailForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-dialog title="门店列表" :visible.sync="dialogDataVisible">
      <el-table :data="tableData" width="100%" ref="ref_table" @select="handleSelectionChange">
        <el-table-column fixed type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="brief" label="简介">
          <template slot-scope="{row: {brief}}">
            <span>{{brief | subStr(10)}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="muse_pagination"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="paging.pageSizeAry"
        :page-size="paging.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fnClosePopup">取 消</el-button>
        <el-button type="primary" @click="fnSaveChoosed">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import simpleRich from "@/components/muse/simple-rich/simple-rich";
import banner from "@/components/muse/banner/banner";
import tableMixin from "../mixins/tableMixin";
import uploadMixin from "../mixins/uploadMixin";
import {
  getOneVoucher,
  changeVoucher,
  getStoreList,
  getProductCategoryList,
} from "@/api/admin";
export default {
  name: "changeVoucher",
  components: {
    simpleRich,
    banner,
  },
  mixins: [uploadMixin, tableMixin],
  data() {
    return {
      id: "",
      detailForm: {
        title: "",
        store: [],
        storeName: "",
        originalPrice: "",
        // discountPrice: '',
        point: "",
        description: "",
        buyExpireDate: "",
        buyStartDate: "",
        useExpireDate: "",
        useStartDate: "",
        useExpireType: "",
        useExpireDay: "",
        totalCount: "",
        limit: "",
        images: [],
        detail: [],
        productCategory: "",
        thumbnail: "",
        foreignImage: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        storeName: [
          { required: false, message: "请选择商店", trigger: "blur" },
        ],
        productCategory: [
          { required: false, message: "请选择商城类目", trigger: "blur" },
        ],
        originalPrice: [
          { required: true, message: "请输入原价", trigger: "blur" },
        ],
        // discountPrice: [
        //   { required: true, message: '请输入现价', trigger: 'blur' }
        // ],
        point: [{ required: true, message: "请输入积分", trigger: "blur" }],
        description: [
          { required: false, message: "请输入描述", trigger: "blur" },
        ],
        buyExpireDate: [
          { required: true, message: "请输入购买过期时间", trigger: "blur" },
        ],
        buyStartDate: [
          { required: true, message: "请输入购买开始时间", trigger: "blur" },
        ],
        useExpireDate: [
          { required: true, message: "请输入使用截止时间", trigger: "blur" },
        ],
        useStartDate: [
          {
            required: true,
            message: "请输入允许开始使用时间",
            trigger: "blur",
          },
        ],
        useExpireType: [
          { required: true, message: "请输入有效类型", trigger: "blur" },
        ],
        useExpireDay: [
          { required: false, message: "请输入有效天数", trigger: "blur" },
        ],
        totalCount: [
          { required: true, message: "请输入总发行量", trigger: "blur" },
        ],
        limit: [{ required: true, message: "请输入限领数量", trigger: "blur" }],
        images: [{ required: true, message: "请输入图片", trigger: "blur" }],
        detail: [{ required: false, message: "请输入详情", trigger: "blur" }],
        thumbnail: [
          { required: true, message: "请选择缩略图", trigger: "blur" },
        ],
        foreignImage: [
          { required: true, message: "请选择门店展示图", trigger: "blur" },
        ],
      },
      tableData: [],
      oldStoreList: [],
      choosedDataObj: [],
      dialogDataVisible: false,
      productCategoryList: [],
    };
  },
  created() {
    this.id = this.$route.query.id;
    if (this.id) {
      this.getOneVoucher();
    }

    this.getProductCategoryList();
  },
  methods: {
    // 得到活动详情
    async getOneVoucher() {
      const res = await getOneVoucher({ id: this.id });
      this.detailForm = res.data;
      this.choosedDataObj = this.detailForm.store;
      this.oldStoreList = this.choosedDataObj;
      this.detailForm.productCategory = this.detailForm.productCategory[0];
      this.fnFormatData();
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.id) {
            this.detailForm["id"] = this.id;
          }
          console.log(123, this.detailForm);
          const res = await changeVoucher(this.detailForm);
          this.$router.push({ name: "voucherList" });
        } else {
          return false;
        }
      });
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 打开门店弹框
    fnOpenPopup() {
      this.dialogDataVisible = true;
      this.getTableData();
    },
    fnClosePopup() {
      this.dialogDataVisible = false;
      this.choosedDataObj = [];
      this.choosedDataObj = this.oldStoreList;
    },
    // 获得门店列表
    async getTableData(value, type) {
      let params = {
        page:
          type === "page"
            ? value
              ? value
              : this.paging.page
            : this.paging.page,
        pageSize:
          type === "pageSize"
            ? value
              ? value
              : this.paging.pageSize
            : this.paging.pageSize,
      };
      const {
        code,
        data: { total, currentPage, data, pageSize },
      } = await getStoreList(params);
      this.paging.total = total;
      this.paging.pageSize = pageSize;
      this.paging.page = currentPage;
      this.tableData = data;

      const showAry = this.tableData.filter((item) => {
        for (let i = 0; i < this.choosedDataObj.length; i++) {
          if (item._id === this.choosedDataObj[i]._id) {
            return true;
          }
        }
      });

      this.$nextTick(() => {
        showAry.forEach((item) => {
          this.$refs.ref_table.toggleRowSelection(item, true);
        });
      });
    },
    // 获得商城类目列表
    async getProductCategoryList(value, type) {
      let params = {
        page: 1,
        pageSize: 100,
      };
      const {
        code,
        data: { data },
      } = await getProductCategoryList(params);
      this.productCategoryList = data;
    },
    fnSaveChoosed() {
      this.fnFormatData();
      this.fnClosePopup();
    },
    /**
     * @description: 当多选门店是处理数据
     * @param {type}
     * @return:
     */
    fnFormatData() {
      this.detailForm.store = [];
      this.detailForm.storeName = [];
      this.choosedDataObj.forEach((item) => {
        this.detailForm.store.push(item._id);
        this.detailForm.storeName.push(item.name);
      });
      this.oldStoreList = this.choosedDataObj;
    },
    // 弹框选择项编辑
    handleSelectionChange(valueAry, value) {
      console.log(this.choosedDataObj,value)
     if (valueAry.length > 1) {
         this.$refs.ref_table.clearSelection()
         this.$refs.ref_table.toggleRowSelection(valueAry[valueAry.length-1])
     }
     this.choosedDataObj = [value]
      // return
      // let tempList = this.choosedDataObj
      // this.choosedDataObj = this.choosedDataObj.map((item) => {
      //   return JSON.stringify(item);
      // });
      // if (this.choosedDataObj.indexOf(JSON.stringify(value)) > -1) {
      //   this.choosedDataObj.splice(
      //     this.choosedDataObj.indexOf(JSON.stringify(value)),
      //     1
      //   );
      // } else {
      //   this.choosedDataObj.push(JSON.stringify(value));
      // }
      // if(this.choosedDataObj.length>1){
      //   this.$alert('只能选择一个门店', '提示', {
      //     confirmButtonText: '确定',
      //     callback: action => {}
      //     });
      //     return this.choosedDataObj = tempList
      // }
      // this.choosedDataObj = this.choosedDataObj.map((item) => {
      //   return JSON.parse(item);
      // });
    },
    async handleAvatarSuccess(file, type, index) {
      const url = await this.fnUpload(file);
      this.detailForm[type] = url;
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped>
.from_width {
  width: 40%;
}
</style>
